package com.sunnada.weixin.util.weixinPay;



import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sunnada.weixin.util.weixinPay.Constant;
import com.sunnada.weixin.util.weixinPay.DateEasy;
import com.sunnada.weixin.util.weixinPay.SecurityUtil;

public class BusiUtil {
	
	private static final Logger log = LoggerFactory.getLogger(BusiUtil.class);

	private static Object obj = new Object();
	
	private static long count = 0;
	
	public static String createOutTradeNo() {
		synchronized (obj) {
			count++;
			String sCount = String.valueOf(count);
			if(sCount.length() > 18) {
				count = 0;
				sCount = String.valueOf(count);
			}
			return new DateEasy().toYYYYMMDDHHMMSS() + StringUtils.leftPad(sCount, 18, "0");
		}
	}
	
	/**
	 * 获取请求参数排序字符串
	 * <p>Description: 排序  取出全部的参数与值，按照每个参数的进行ascII码排续</p>
	 * @param paramsMap 请求参数
	 * @return
	 */
	public static String paramsSort(Map<String, String> paramsMap){
		StringBuffer sb=new StringBuffer();
		Object[] key_arr = paramsMap.keySet().toArray();
		Arrays.sort(key_arr);
		for (Object key : key_arr) {
			Object value = paramsMap.get(key);
			if(!"sign".equals(key))
				sb.append(key).append("=").append(value).append("&");
		}
		if(sb.length() > 0) {
			sb.delete(sb.length()-1, sb.length());
		}
		return sb.toString();
	}
	
	/**
	 * 验证请求参数的合法性
	 * <p>Description: </p> 
	 * @param queryString 排序后的参数字符串+密文
	 * @param sign 签名
	 * @return
	 */
	public static boolean checkParams(String queryString,String mch_key,String sign){
		if(queryString!=null && !"".equals(queryString)){
			String source=queryString+"&key="+mch_key;
			String validate=SecurityUtil.MD5Encrypt(source);
			log.debug("被签名字符串："+source);
			log.debug("正确的签名字符串:"+validate);
			return sign.equals(validate);
		}else
			return false;
	}
	
	public static boolean checkParams(Map<String, String> params,String mch_key){
		return checkParams(paramsSort(params),mch_key,params.remove("sign"));
	}
	
	/**
	 * 获取签名
	 * <p>Description: </p> 
	 * @param queryString 排序后的参数字符串
	 * @return
	 */
	public static String getSign(String queryString, String key){
		queryString = queryString+"&key="+key;
		log.info("被签名字符串："+queryString);
		log.info("正确的签名字符串:"+SecurityUtil.MD5Encrypt(queryString));
		return SecurityUtil.MD5Encrypt(queryString);
	}
	
	public static String getSign(Map<String, String> paramsMap, String key){
		return getSign(paramsSort(paramsMap), key);
	}
	
	public static void main(String[] args) {
		/*int count = 5;
		final CountDownLatch latch = new CountDownLatch(count);
		for(int j=0; j<count; j++) {
			new Thread(){
				public void run() {
					for(int i=0; i<20; i++) {
						System.out.println(createOutTradeNo());
					}
					latch.countDown();
				};
			}.start();
		}
		try {
			latch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}*/
		
		Map<String, String> params = new HashMap<String, String>();
		params.put("appid", "wxd930ea5d5a258f4f");
		params.put("mch_id", "10000100");
		params.put("device_info", "1000");
		params.put("body", "test");
		params.put("nonce_str", "ibuaiVcKdpRxkhJA");
		String signParam = paramsSort(params);
		System.out.println(signParam);
		String mch_key = "192006250b4c09247ec02edce69f6a2d";
		signParam = signParam + "&key=" + mch_key;
		String sign = SecurityUtil.MD5Encrypt(signParam);
		System.out.println(sign);
		params.put("sign", sign);
		
		System.out.println(EObject2XML.mapToXml(params));
		
		System.out.println(Sign.create_nonce_str().replace("-", ""));
		
		System.out.println(EObject2XML.mapToXml(JSONObject.toJavaObject(JSON.parseObject(JSON
				.toJSONString(params)), Map.class)));
		
		
		String str="appid=wx15b75d1862da1d48&attach=151222114300007&bank_type=CFT&cash_fee=1&fee_type=CNY&is_subscribe=Y&mch_id=1277670701&nonce_str=7fd5d8d0b96a40f4a1530d6617b07266&openid=ojMcpxP76PcxsEKnBUWWT4kvSQm8&out_trade_no=20151222114331000000000000000005&result_code=SUCCESS&return_code=SUCCESS&time_end=20151222114332&total_fee=1&trade_type=JSAPI&transaction_id=1002370360201512222234820069&key=f5ebe493b35c42b29b71b308bc4588a0";
		System.out.println(SecurityUtil.MD5Encrypt(str));
	}
}
